import { v4 as uuid } from 'uuid';

export function formatChargeTime(seconds:number) {
  var hours = Math.floor(seconds / 3600);  
  var minutes = Math.floor((seconds % 3600) / 60);
  let str = ''
  if(hours > 0) {
    str += `${hours}小时`
  }

  if(minutes > 0) {
    str += `${minutes}分钟`
  }

  return str
}

export function parseTime(time:any, cFormat:string='{y}-{m}-{d} {h}:{i}:{s}') {
	if(time == 0 || time == null){
		return ''
	}
	
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (!isNaN(time) && ('' + time).length === 10) time = parseInt(time) * 1000

    date = new Date(time)
  }

  const formatObj:any = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
	
  return time_str
}

export function recursionFn<T=any>(source:{[key:string] : any}[], parentId:any, keyField = 'id', parentField = 'parentId', childrenName = 'children') :T[]{
  let target:T[] = []
  function fn(s:{[key:string] : any}[], t:any[], p:any) {
    s.forEach(item => {
      if(item[parentField] == p) {
        t.push(item)
        item[childrenName] = []
        fn(s, item[childrenName], item[keyField])
        if(item[childrenName].length == 0) {
            delete item[childrenName]
        }
      }
    })
  }

  fn(source, target, parentId)

  return target
}

export function recursionIndexValues(source:{[key:string] : any}[], index:number, valueField:string, childrenField:string='children') {
  let values:any[] = []
  function fn(source:{[key:string] : any}[]) {
    values.push(source[index][valueField])
    if(source[index][childrenField] && source[index][childrenField].length > 0) {
      fn(source[index][childrenField])
    }
  }

  fn(source)

  return values
}

export function filterEmptyParam(params:{[key:string] : any}) {
  let _params:{[key:string] : any} = {}
  function filter(data:{[key:string] : any}, target:{[key:string] : any}) {
    for(let k in data) {
      if(data[k] !== undefined && data[k] !== '' && data[k] !== null) {
        if(typeof data[k] === 'object') {
          target[k] = {}
          filter(data[k], target[k])
        }else {
            target[k] = data[k]
        }
      }
    }
  }

  filter(params, _params)

  return _params
}


export async function readCsv(file:File) :Promise<Array<{[key:string]:any}>>{
  const reader = new FileReader()
  const rows:Array<{[key:string]:any}> = []

  return new Promise((resolve, reject) => {
    reader.onload = async function (res) {
      if(res.target) {
          const arr = res.target.result.split('\r\n')
          if(arr.length > 0) {
            let headers = arr.shift().split(',')

            arr.forEach(item => {
              if(item !== '') {
                const row:{[key:string]:any} = {}
                const items = item.split(',')
                items.forEach((v, i) => {
                  row[headers[i]] = v
                })

                rows.push(row)
              }
              
            })

          }
          
      }

      resolve(rows)
    }
  
    reader.readAsText(file)
  })

  
}


export function downloadCsv(fileName:string, data:Array<Array<string|number>>) {
  let csvData:string[] = data.map(item => item.join(','))
  let alink = document.createElement("a");
  let _utf = "\uFEFF"; // 解决中文乱码的问题，标识该字节流的字节序
  const csvDataBlob = new Blob([_utf + csvData.join('\r\n')], {
      type: "text/csv",
  });
  alink.href = URL.createObjectURL(csvDataBlob); 
  document.body.appendChild(alink);
  alink.setAttribute("download", fileName + '.csv');
  alink.click();
  document.body.removeChild(alink);
}


export function isValidMobileNumber(mobile:string) {
  // 中国大陆手机号码格式正则表达式，以1开头，后10位是0-9的数字
  var mobilePattern = /^1[3-9]\d{9}$/;
  return mobilePattern.test(mobile);
}


export function formatVisitNumber(num:number) {
  if(num < 1000) return num
  if(num < 10000) return Number((num / 1000).toFixed(1)) + 'K'
  return Number((num / 10000).toFixed(1)) + 'W'
}


export function generateCodeFromUid() :string{
  let arr = uuid().split("-")
  return arr[1] + arr[3];
}